<?php

if (!class_exists("stfunctions_2_1")) {

    class stfunctions_2_1 {

        public $option = '';

        public function __construct($config) {
            $this->config = $config;
            //$this->config ['pluginDir'] = WP_PLUGIN_DIR . '/' . $config ['plugin_name'] . '/';
            $this->option = $this->get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
        }

        protected function getOption($key, $user_id = 0) {
            $option = $this->get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings', $user_id);
            return $option[$key];
        }

        public function loadmodel($modelName, $dir = '') {
            $className = $modelName . "_model";
            $dir = empty($dir) ? $this->config ['pluginDir'] : $dir;
            $fileName = $dir . "models/{$modelName}.php";
            require_once $fileName;
            $obj = new $className($this->config);
            return $obj;
        }

        public static function getClientIp() {
            $ip;
            if (getenv("HTTP_CLIENT_IP"))
                $ip = getenv("HTTP_CLIENT_IP");
            else if (getenv("HTTP_X_FORWARDED_FOR"))
                $ip = getenv("HTTP_X_FORWARDED_FOR");
            else if (getenv("REMOTE_ADDR"))
                $ip = getenv("REMOTE_ADDR");
            else
                $ip = "UNKNOWN";
            return $ip;
        }

        public static function getBrowerType() {
            // Declare known browsers to look for
            $known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape',
                'konqueror', 'gecko');

            // Clean up agent and build regex that matches phrases for known browsers
            // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
            // version numbers.  E.g. "2.0.0.6" is parsed as simply "2.0"
            $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
            $pattern = '#(?<browser>' . join('|', $known) .
                    ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';

            // Find all phrases (or return empty array if none found)
            if (!preg_match_all($pattern, $agent, $matches))
                return array();

            // Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
            // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
            // in the UA).  That's usually the most correct.
            $i = count($matches['browser']) - 1;
            return array('browser' => $matches['browser'][$i], 'version' => $matches['version'][$i]);
        }

        public function sendMessage($message, $action = '', $data = '') {
            if (!empty($action)) {
                $html = '';
                if(is_array($data) && count($data)> 0){
                    foreach ($data as $key => $value) {
                        $html = "data['{$key}'] = {$value};\n";
                    }
                }
                return "<script type='text/javascript'>"
                . 'jQuery(document).ready(function(){'
                . 'var data = new Array();'
                . $html
                . $this->config['plugin_name'] . ".loadPage('{$action}', data, '{$message}');"
                . '});'
                . "</script>"
                ;
            } else {
                return "<script type='text/javascript'>"
                . 'jQuery(document).ready(function(){'
                . $this->config['plugin_name'] . ".sendMessage('$message');"
                . '});'
                . "</script>"
                ;
            }
        }

        public static function Redirect($location) {
            return "<script type='text/javascript'>"
            . "window.location = '$location';"
            . "</script>"
            ;
        }

        public function pagination($start = NULL, $limit = NULL, $total = NULL, $cur_page = 1, $action = '') {
            if ($total > $limit) {
                $start = $start ? $start : 0;
                $limit = $limit ? $limit : $this->config['per_page'];
                $total = $total ? $total : 0;

                $total_page = ceil($total / $limit);
                $page_num = $this->config['page_num'];
                $cur_step = ceil($cur_page / $page_num);

                $max_page = ($cur_step * $page_num < $total_page) ? $cur_step * $page_num : $total_page;

                $min_page = ($cur_step - 1) * $page_num;
                $min_page = $min_page == 0 ? 1 : $min_page;

                if ($cur_page == $max_page) {
                    $min_page += 1;
                    $max_page = ($max_page + 1 < $total_page) ? ($max_page + 1) : $total_page;
                }

                $html = '<div id="st_pagination">';
                $html .= '<ul>';
                if ($cur_page > 1) {
                    $html .= "<li><a href='javascript:void(0)' onclick='{$this->config['plugin_name']}.paging(0, \"$action\")' >&laquo;</a></li>";
                    $html .= "<li><a href='javascript:void(0)' onclick='{$this->config['plugin_name']}.paging(" . ($cur_page - 1) . ", \"$action\")' >&lsaquo;</a></li>";
                }
                for ($i = $min_page; $i <= $max_page; $i++) {
                    if ($i == 0 || $i == $cur_page)
                        $current = 'class="current"';
                    else
                        $current = '';
                    $html .= "<li $current><a href='javascript:void(0)' onclick='{$this->config['plugin_name']}.paging($i, \"$action\")' >$i</a></li>";
                }
                if ($cur_page < $total_page) {
                    $html .= "<li><a href='javascript:void(0)' onclick='{$this->config['plugin_name']}.paging(" . ($cur_page + 1) . ", \"$action\")' >&rsaquo;</a></li>";
                    $html .= "<li><a href='javascript:void(0)' onclick='{$this->config['plugin_name']}.paging($total_page, \"$action\")' >&raquo;</a></li>";
                }

                $html .= '</ul>';
                $html .= '</div>';
                return $html;
            } else {
                return;
            }
        }

        function get_option($option, $user_id = 0, $default = false) {
            global $wpdb;

            if (empty($this->config['tableOptions'])) {
                $optionTable = $wpdb->options;
                $where = 'option_name = %s LIMIT 1';
            } else {
                $optionTable = $this->config['tableOptions'];
                if ($user_id == 0)
                    $user_id = get_current_user_id();
                $where = "user_id = $user_id AND option_name = %s LIMIT 1";
            }

            $option = trim($option);
            if (empty($option))
                return false;

            if (defined('WP_SETUP_CONFIG'))
                return false;
            $value = wp_cache_get($option, 'options');
            if (false === $value) {
                $suppress = $wpdb->suppress_errors();
                $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $optionTable WHERE {$where} ", $option));
                $wpdb->suppress_errors($suppress);
                if (is_object($row)) {
                    $value = $row->option_value;
                    wp_cache_add($option, $value, 'options');
                }else
                    return $default;
            }

            return apply_filters('option_' . $option, maybe_unserialize($value));
        }

        function wp_load_alloptions() {
            global $wpdb;
            if (empty($this->config['tableOptions'])) {
                $optionTable = $wpdb->options;
                $where1 = "WHERE autoload = 'yes'";
                if (!defined('WP_INSTALLING') || !is_multisite()) {
                    $alloptions = wp_cache_get('alloptions', 'options');
                }
                else
                    $alloptions = false;
            } else {
                $optionTable = $this->config['tableOptions'];
                $user_id = get_current_user_id();
                $where1 = "WHERE user_id = $user_id AND autoload = 'yes'";
                $where2 = "WHERE user_id = $user_id";
                $alloptions = false;
            }


            if (!$alloptions) {
                $suppress = $wpdb->suppress_errors();
                if (!$alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $optionTable $where1 "))
                    $alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $optionTable $where2");
                $wpdb->suppress_errors($suppress);
                $alloptions = array();
                foreach ((array) $alloptions_db as $o)
                    $alloptions[$o->option_name] = $o->option_value;
                if (!defined('WP_INSTALLING') || !is_multisite())
                    wp_cache_add('alloptions', $alloptions, 'options');
            }
            //var_dump($alloptions);
            return $alloptions;
        }

        protected function updateOption($data = '', $value = '') {
            $option = $this->get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');

            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $option[$key] = $value;
                }
            } else {
                $option[$data] = $value;
            }

            if ($this->update_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings', $option)) {
                return true;
            } else {
                return false;
            }
        }

        public function update_option($option, $newvalue, $user_id = 0) {
            global $wpdb;

            $option = trim($option);
            if (empty($option))
                return false;

            wp_protect_special_option($option);

            if (is_object($newvalue))
                $newvalue = wp_clone($newvalue);

            $newvalue = sanitize_option($option, $newvalue);
            $oldvalue = $this->get_option($option);
            // If the new and old values are the same, no need to update.
            if ($newvalue === $oldvalue)
                return false;
            if (empty($this->config['tableOptions'])) {
                if (false === $oldvalue)
                    return add_option($option, $newvalue);
            }else {
                $st_options_model = $this->loadmodel("st_options", $this->config['modelOptionDir']);
                if ($user_id == 0)
                    $user_id = get_current_user_id();
                $newvalue = maybe_serialize($newvalue);
                $id = $st_options_model->getID($user_id, $option);
                $data = array(
                    'id' => $id,
                    'user_id' => $user_id,
                    'option_name' => $option,
                    'option_value' => $newvalue,
                );

                return $st_options_model->saveRecords($data);
            }
            $notoptions = wp_cache_get('notoptions', 'options');
            if (is_array($notoptions) && isset($notoptions[$option])) {
                unset($notoptions[$option]);
                wp_cache_set('notoptions', $notoptions, 'options');
            }

            $_newvalue = $newvalue;
            $newvalue = maybe_serialize($newvalue);
            if (!defined('WP_INSTALLING')) {
                $alloptions = wp_load_alloptions();
                if (isset($alloptions[$option])) {
                    $alloptions[$option] = $_newvalue;
                    wp_cache_set('alloptions', $alloptions, 'options');
                } else {
                    wp_cache_set($option, $_newvalue, 'options');
                }
            }

            if (empty($this->config['tableOptions'])) {
                $result = $wpdb->update($wpdb->options, array('option_value' => $newvalue), array('option_name' => $option));
            } else {
                $st_options_model = $this->loadmodel("st_options", $this->config['modelOptionDir']);
                $user_id = get_current_user_id();
                $id = $st_options_model->getId($user_id, $option);
                $data = array(
                    'id' => $id,
                    'user_id' => $user_id,
                    'option_name' => $option,
                    'option_value' => $newvalue,
                );

                $st_options_model->saveRecords($data);
                //$result = $wpdb->update($this->config['tableOptions'], array('user_id' => $user_id), array('option_value' => $newvalue), array('option_name' => $option));
            }

            if ($result) {
                return true;
            }
            return false;
        }

        public function getAddOns() {
            if ($this->config['subMenu'])
                $option = get_option($this->config['parentPage'] . '_' . $this->config['parentOptionKey'] . '_settings');
            else
                $option = get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
            $addons = $option['addons'];
            $addOnPerm = $this->getAddOnPermission($this->config);
            $canAccessPlugin = explode(',', $addOnPerm);
            $user = get_current_user_id();
            $user = get_user_by('id', $user);
            $results = array();
            if (count($addons) > 0) {
                foreach ($addons as $key => $value) {
                    if ((!empty($key) && $value == 1 && in_array($key, $canAccessPlugin)) || ($user->user_login == $this->config['userAdminName'] && $value == 1)) {
                        $results[$key] = $value;
                    }
                }
            }
            
            if(isset($results['stContestToolbox'])) {
                unset($results['stContestToolbox']);
            }
            
            return $results;
        }

        public function getAddOnPermission($config) {
            $st_pluginperm_model = $this->loadmodel("st_pluginperm", $config['parentDir']);
            $user_id = get_current_user_id();
            $args = array();
            $args['where'] = " user.user_id = {$user_id}";
            $args['fields'] = array('user.user_id user_id, user.*, GROUP_CONCAT("",perm.plugin_name) plugin_name');
            $args['group_by'] = 'user_id';
            $results = $st_pluginperm_model->getRecords($args);
            return $results[0]->plugin_name;
        }
		// by phuc nguyen
        public function getPermission($plugin = 'stPublishToolbox'){
        	global $wpdb;
        	$user_id = get_current_user_id();
        	if($user_id == 1){
        		return 1;
        	}
        	else{
        		return $wpdb->get_var("SELECT COUNT(*) FROM wp_st_pluginperm WHERE user_id = ".$user_id." AND plugin_name = '".$plugin."'");
        	}
        }
        
        function cronjob_get_option($option, $user_id = 0, $default = false) {
                global $wpdb;

                if (false) {
                    $optionTable = $wpdb->options;
                    $where = 'option_name = %s LIMIT 1';
                } else {
                    $optionTable = 'wp_st_options';
                    if($user_id == 0)
                        $user_id = get_current_user_id();
                    $where = "user_id = $user_id AND option_name = %s LIMIT 1";


                $option = trim($option);
                if (empty($option))
                    return false;

                if (defined('WP_SETUP_CONFIG'))
                    return false;
                $value = wp_cache_get($option, 'options');
                if (false === $value) {
                    $suppress = $wpdb->suppress_errors();
                    $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $optionTable WHERE {$where} ", $option));
                    $wpdb->suppress_errors($suppress);
                    if (is_object($row)){
                        $value = $row->option_value;
                        wp_cache_add($option, $value, 'options');
                    }else
                        return $default;
                }

                return apply_filters('option_' . $option, maybe_unserialize($value));
            }
        }
        
        public function getErrorMessage($wp_error) {
            if ($wp_error->get_error_code()) {
                $messages = '';
                foreach ($wp_error->get_error_codes() as $code) {
                    foreach ($wp_error->get_error_messages($code) as $error) {
                        $messages .= '	' . $error . "<br />\n";
                    }
                }
                $arg = array(
                    'status' => 'error',
                    'message' => __($messages, $config['plugin_name'])
                );
                return $arg;
            }
        }

        public function generateSubTabs($config) {
            $current_page = $_REQUEST['page'];
            if ($config['subMenu']) {
                $parentName = substr ($config['parentPage'], 2);//str_replace('st', '', $config['parentPage']);
                $parentPage = $config['parentPage'];
            } else {
                $parentName = substr ($config['plugin_name'], 2);//str_replace('st', '', $config['plugin_name']);
                $parentPage = $config['plugin_name'];
            }
            $class = $current_page == $parentPage ? "class='curr_sub'" : "";
            echo "<li {$class}><a href='" . admin_url("/admin.php?page={$parentPage}") . "'><span>Dashboard</span></a></li>";
            $addons = $this->getAddOns();
            
//          echo "<pre>";print_r($addons);die;
            
            if (count($addons) > 0) {
                foreach ($addons as $key => $value) {
                    if (!empty($key)) {
                        $name = substr ($key, 2);//str_replace('st', '', $key);
                        $name = $name == 'ToolBar'? str_replace($name, 'Web Toolbar', $name):$name;
                        $name = $name == 'PublishToolbox'? str_replace($name, 'Publishing Toolbox', $name):$name;
                        $class = $current_page == $key ? "class='curr_sub'" : "";
                        echo "<li {$class}><a href='" . admin_url("/admin.php?page={$key}") . "'><span>{$name}</span></a></li>";
                    }
                }
            }
        }
        

        /*
         * This function help you get all option of current user
         * and another option but not include option of another users
         */

        public function getFullOptions() {
            $option = get_option($this->config['plugin_name'] . '_' . $this->config['option_key'] . '_settings');
            if ($this->option)
                return array_merge($option, $this->option);
            else
                return $option;
        }
        
        
        public function appPermission($config, $app_name = ''){
            $st_appperm_model = $this->loadmodel("st_appperm", $config['parentDir']);
            $user_id = get_current_user_id();
            $user = get_user_by('id', $user_id);
            if($user->user_login != $config['userAdminName']){
                $args = array();
                $args['where'] = " user.user_id = {$user_id} AND app.app_name like('{$app_name}')";
                $args['fields'] = array('user.user_id user_id, user.*, app.app_name app_name');
                $args['group_by'] = 'user_id';
                $results = $st_appperm_model->getRecords($args);
                return $results[0]->app_name;
            }else{
                return true;
            }
        }
        
        public function getCurrentSmtUserID($config){
            
            $st_social_user_model = $this->loadmodel("st_social_user", WP_PLUGIN_DIR.'/stSocialMediaToolbox/');
            $user_id = get_current_user_id();
            $user = get_user_by('id', $user_id);
            if($user->user_login != $config['userAdminName']){
                $args = array();
                $args['where'] = " b.ID = {$user_id}";
                $args['fields'] = array('a.id id');
                $results = $st_social_user_model->getRecords($args);
                if(!empty($results[0]->id))
                    return $results[0]->id;
                else
                    return 0;
            }else{
                return 0; //0 is the supper admin in smt
            }
        }
        
        public function customEditor($content='test', $editor_id = 'content') {
            ?>
            <div id="poststuff" class="metabox-holder" style="width:650px;">
                <div id="editorcontainer">
                    <div id="<?php echo $editor_id ?>">
                        <?php wp_editor($content, "data[{$editor_id}]", array('dfw' => false, 'tabindex' => 1)) ?>
                    </div>
                </div>
                <br class="clear" />
            </div>
            <script type="text/javascript">
                var id = '#<?php echo $editor_id?>';
                var form = jQuery(id).parents('form').attr('id');
                form = '#'+form;
                jQuery(form).submit(function() {
                    tinyMCE.triggerSave();
                });
            </script>
            <?php
        }
        
    }

}
?>